
//create all the variables
var score;
var cardsmatched;

var ui = $("#gameUI");
//var uiIntro = $("#gameIntro");
var uiStats = $("#gameStats");
var uiComplete = $("#gameComplete");
var uiCards= $("#cards");
var uiReset = $(".gameReset");
var uiScore = $(".gameScore");
var uiPlay = $("#gamePlay");
var uiTimer = $("#timer");
var uiNext=$("#next");
var scoreTimeout=0;
var uiQuit =$("#quit");

//create deck array
var matchingGame = {};
matchingGame.deck = [
'blueDino', 'blueDino',
'brownDino', 'brownDino',
'greenDino', 'greenDino',
'burgDino', 'burgDino',
'orangeDino', 'orangeDino',
'purp2Dino', 'purp2Dino',
'pinkDino', 'pinkDino',
];


//Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);


// PhoneGap is ready
//
function onDeviceReady() {
    //playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3");
}

//Audio player
//
var my_media = null;
var mediaTimer = null;


//on document load the lazy way
$(function(){
	  init();
});

//initialise game
function init() {
					uiComplete.hide();
					uiCards.hide();
					playGame = false;
					startGame();
			/* 		uiPlay.click(function(e) {
						e.preventDefault();
					//	uiIntro.hide();
						startGame();
					}); */
				
					uiReset.click(function(e) {
						e.preventDefault();
						playAudio("/android_asset/www/sounds/buttonClick.mp3");
						uiComplete.hide();					
						reStartGame();
					});
					
				     uiNext.click(function(e) {
						e.preventDefault();
						playAudio("/android_asset/www/sounds/buttonClick.mp3");
						location.href="index16.html";
					});
				     
				     

						uiQuit.click(function(e) {
							e.preventDefault();
							playAudio("/android_asset/www/sounds/buttonClick.mp3");
							 location.href="menu.html";
	                  
						});
			}

//start game and create cards from deck array
function startGame(){
				uiTimer.show();
				uiScore.html("0 seconds");
				uiStats.show();
				uiCards.show();
				score = 0;
				cardsmatched = 0;
			   	if (playGame == false) {
			   			playGame = true;
						matchingGame.deck.sort(shuffle);
						for(var i=0;i<13;i++){
								$(".card:first-child").clone().appendTo("#cards");
							}
							// initialize each card's position
							uiCards.children().each(function(index) {
								// align the cards to be 3x6 ourselves.
								$(this).css({
									"left" : ($(this).width() + 20) * (index % 5),
									"top" : ($(this).height() + 20) * Math.floor(index / 5)
								});
								// get a pattern from the shuffled deck
								var pattern = matchingGame.deck.pop();
								// visually apply the pattern on the card's back side.
								$(this).find(".back").addClass(pattern);
								// embed the pattern data into the DOM element.
								$(this).attr("data-pattern",pattern);
								// listen the click event on each card DIV element.
								$(this).click(selectCard);
							});											 
				   	timer();
				};			   
			  }


//timer for game
function timer() {
				//alert("timer set")
				if (playGame) {
					scoreTimeout = setTimeout(function() {
						uiScore.html(++score + " seconds");		
						timer();
					}, 1000);
				};
		};

//shuffle cards
function shuffle() {
	return 0.5 - Math.random();
}

//onclick function add flip class and then check to see if cards are the same
function selectCard() {
	// we do nothing if there are already two cards flipped.
	if ($(".card-flipped").size() > 1) {
	return;
	}
	playAudio("/android_asset/www/sounds/flip.mp3");///////////////////////////////////////////sound
	$(this).addClass("card-flipped");
	// check the pattern of both flipped card 0.7s later.
	if ($(".card-flipped").size() == 2) {
	setTimeout(checkPattern,700);
	}
}

//if pattern is same remove cards otherwise flip back
function checkPattern() {
	if (isMatchPattern()) {
		$(".card-flipped").removeClass("card-flipped").addClass("card-removed");
			if(document.webkitTransitionEnd){
				$(".card-removed").bind("webkitTransitionEnd",	removeTookCards);
			}else{
				removeTookCards();
			}
		} else {
		$(".card-flipped").removeClass("card-flipped");
	}
}

//put 2 flipped cards in an array then check the image to see if it's the same.
function isMatchPattern() {
	var cards = $(".card-flipped");
	var pattern = $(cards[0]).data("pattern");
	var anotherPattern = $(cards[1]).data("pattern");
	return (pattern == anotherPattern);
}

//check to see if all cardmatched variable is less than 8 if so remove card only otherwise remove card and end game 
function removeTookCards() {
	if (cardsmatched < 6){
		cardsmatched++;
		$(".card-removed").remove();
	}else{
		$(".card-removed").remove();
		uiCards.hide();
		uiComplete.show();
		clearTimeout(scoreTimeout);
	}	
}

//recreate the original card , stop the timer and re populate the array with class names
function reStartGame(){
				playGame = false;
				uiCards.html("<div class='card'><div class='face front'></div><div class='face back'></div></div>");
				clearTimeout(scoreTimeout);
				matchingGame.deck = [
				'blueDino', 'blueDino',
                'brownDino', 'brownDino',
                'greenDino', 'greenDino',
                'burgDino', 'burgDino',
                'orangeDino', 'orangeDino',
                 'purp2Dino', 'purp2Dino',
               'pinkDino', 'pinkDino',];			
				startGame();
			}
				

//***********************************************************Audio Part******************************************************************//
//Play audio
//
function playAudio(src) {
 // Create Media object from src
 my_media = new Media(src, onSuccess, onError);

 // Play audio
 my_media.play();

 // Update my_media position every second
 if (mediaTimer == null) {
     mediaTimer = setInterval(function() {
         // get my_media position
         my_media.getCurrentPosition(
             // success callback
             function(position) {
                 if (position > -1) {
                     setAudioPosition((position) + " sec");
                 }
             },
             // error callback
             function(e) {
                 console.log("Error getting pos=" + e);
                 setAudioPosition("Error: " + e);
             }
         );
     }, 1000);
 }
}

//Pause audio
//
function pauseAudio() {
 if (my_media) {
     my_media.pause();
 }
}

//Stop audio
//
function stopAudio() {
 if (my_media) {
     my_media.stop();
 }
 clearInterval(mediaTimer);
 mediaTimer = null;
}

//onSuccess Callback
//
function onSuccess() {
 console.log("playAudio():Audio Success");
}

//onError Callback 
//
function onError(error) {
 alert('code: '    + error.code    + '\n' + 
       'message: ' + error.message + '\n');
}

//Set audio position
//
function setAudioPosition(position) {
// document.getElementById('audio_position').innerHTML = position;
}
